import Vue from 'vue'
import VueRouter from 'vue-router'
import { nav, genNav } from '../api/sys/menu'
import routes from './routes'
import Store from '../store'

Vue.use(VueRouter)

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default function (/* { store, ssrContext } */) {
  const Router = new VueRouter({
    scrollBehavior: () => ({
      x: 0,
      y: 0
    }),
    routes,

    // Leave these as they are and change in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE
  })

  Router.beforeEach((to, from, next) => {
    let isLoadNav = Store().getters.isLoadNav
    if (!isLoadNav){
      // 动态加载路由
      nav().then((result) => {
        const nav = routes[0]
        const newList = genNav(result.data.data)
        nav.children.push(...newList)
        Store().commit('nav/loadNav')
        Router.addRoutes(routes)
        console.log('第一次加载动态路由')
        next({ ...to, replace: true })
      })
    }else {
      next()
    }
  })

  return Router
}
